package com.ants.project.core.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * HttpClient 请求
 * 账号模拟登入系统
 * Session模拟登入系统
 * cookieLogin模板登入系统
 * Created by liushun on 2016/4/9.
 */
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 发送Post请求
     *
     * @param url      请求url
     * @param params   数据map
     * @param headers  头信息map
     * @param encoding 编码集
     * @return
     */
    public static String sendPost(String url, Map params, Map headers, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httPost = new HttpPost(url);
        String response = "";
        try {
            List list = new ArrayList();
            //设置参数
            if (params != null) {
                Iterator iterator = params.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry entry = (Entry) iterator.next();
                    list.add(new BasicNameValuePair(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())));
                }
            }
            //添加http头信息
            if (headers != null) {
                Iterator iterator = headers.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry entry = (Entry) iterator.next();
                    httPost.addHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); //认证token
                }
            }
            httPost.setEntity(new UrlEncodedFormEntity(list));
            CloseableHttpResponse execute = client.execute(httPost);
            int code = execute.getStatusLine().getStatusCode();
            if (code == 200) {
                HttpEntity entity = execute.getEntity();
                response = EntityUtils.toString(entity, encoding);
            } else {
                logger.info(code + "web request is eror !");
            }
        } catch (Exception e) {
            logger.error("web request is eror !" + e.getMessage());
        }
        return response;
    }

    public static String sendPost(String url, Map params, String encoding) {
        return sendPost(url, params, null, encoding);
    }

    public static String sendPost(String url, Map params) {
        return sendPost(url, params, null, "utf-8");
    }

    /**
     * 发送Get请求
     *
     * @param url      请求url
     * @param encoding 编码集
     * @param headers  头信息map
     * @return
     */
    public static String sendGet(String url, Map headers, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httGet = new HttpGet(url);
        String response = "";
        try {
            //添加http头信息
            if (headers != null) {
                Iterator iterator = headers.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry entry = (Entry) iterator.next();
                    httGet.addHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); //认证token
                }
            }
            CloseableHttpResponse execute = client.execute(httGet);
            int code = execute.getStatusLine().getStatusCode();
            if (code == 200) {
                HttpEntity entity = execute.getEntity();
                response = EntityUtils.toString(entity, encoding);
            } else {
                logger.info(code + "web request is eror !");
            }
        } catch (Exception e) {
            logger.error("web request is eror !" + e.getMessage());
        }
        return response;
    }

    public static String sendGet(String url, String encoding) {
        return sendGet(url, null, encoding);
    }

    public static String sendGet(String url) {
        return sendGet(url, null, "utf-8");
    }

    /**
     * 利用账号密码模拟登入获取页面html内容
     *
     * @param loginUrl  登入请求地址
     * @param targetUrl 目标页面
     * @param name      账号
     * @param pass      密码
     * @param code      验证码
     * @return
     */
    public static String accountLogin(String loginUrl, String targetUrl, String name, String pass, String code) {
        return "";
    }

    /**
     * 利用SessionID获取页面html内容 注意：服务器session必须没过期
     *
     * @param targetUrl 目标页面
     * @param sessionId 唯一ID
     * @return
     */
    public static String sessionLogin(String targetUrl, String sessionId) {
        return "";
    }

    /**
     * 利用cookie获取页面html内容 注意：本地cookie必须没没有被清除
     * @param targetUrl 目标页面
     * @param cookieMap cookie属性对象
     * @return
     */
//    public static String cookieLogin(String targetUrl, Map cookieMap){
//        return "";
//    }
//
//    // 设置已获取的cookie，查看需要登录后才能查看的页面
//    public static void testGetinfoByLoginCookie() throws Exception, IOException {
//        DefaultHttpClient httpclient = new DefaultHttpClient();
//        CookieStore cookieStore = new BasicCookieStore();
//        BasicClientCookie cookie1 = new BasicClientCookie("ThinkID","6so2foiq4i2200no289dkai227");
//        cookie1.setDomain(".lashou.com");
//        BasicClientCookie cookie2 = new BasicClientCookie("city_b","2419");
//        cookie2.setDomain(".lashou.com");
//        BasicClientCookie cookie3 = new BasicClientCookie("client_key","1459848330x3541c657f598628461073");
//        cookie3.setDomain(".lashou.com");
//        BasicClientCookie cookie4 = new BasicClientCookie("login_name2","15673196342");
//        cookie4.setDomain(".lashou.com");
//        BasicClientCookie cookie5 = new BasicClientCookie("pwd2","f4a95c006e7939b1b7c68cd30c1c79cf");
//        cookie5.setDomain(".lashou.com");
//        cookieStore.addCookie(cookie1);
//        cookieStore.addCookie(cookie2);
//        cookieStore.addCookie(cookie3);
//        cookieStore.addCookie(cookie4);
//        cookieStore.addCookie(cookie5);
//        List<Cookie> cookies = new ArrayList<Cookie>();
//        httpclient.setCookieStore(cookieStore);
//
//        List<Cookie> cookieList = httpclient.getCookieStore().getCookies();
//        for(int i=0;i<cookieList.size();i++){
//            System.out.println("cookie"+i+":"+cookieList.get(i));
//        }
//
//        // 设置已登录的cookie
//        String memberpage = "http://www.lashou.com/account/orders/";
//        HttpGet httpget = new HttpGet(memberpage);
//        HttpResponse response = httpclient.execute(httpget); // 必须是同一个HttpClient！
//        HttpEntity entity = response.getEntity();
//        String html = EntityUtils.toString(entity, "utf-8");
//        httpget.releaseConnection();
//
//        System.out.println(html);
//    }

}
